package org.starapp.rbac.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.starapp.core.persistence.DynamicSpecifications;
import org.starapp.core.persistence.SearchFilter;
import org.starapp.core.security.utils.Digests;
import org.starapp.core.utils.DateProvider;
import org.starapp.core.utils.Encodes;
import org.starapp.rbac.contants.AppContants;
import org.starapp.rbac.dao.UsersDao;
import org.starapp.rbac.entity.Users;
import org.starapp.rbac.exception.ServiceException;
import org.starapp.utils.SecurityUtils;

/**
 * @author wangqiang@cisoft.com.cn
 * 
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class UsersService {

	private DateProvider dateProvider = DateProvider.DEFAULT;

	private UsersDao usersDao;

	@Autowired
	public void setUsersDao(UsersDao usersDao) {
		this.usersDao = usersDao;
	}

	public void setDateProvider(DateProvider dateProvider) {
		this.dateProvider = dateProvider;
	}

	public Users getUsers(String pk) {
		return usersDao.findOne(pk);
	}

	@Transactional(readOnly = false)
	public void saveUsers(Users entity) {
		entryptPassword(entity);
		entity.setRegisterDate(dateProvider.getDate());
		usersDao.save(entity);
	}

	@Transactional(readOnly = false)
	public void deleteUsers(String pk) {
		usersDao.delete(usersDao.findOne(pk));
	}

	@Transactional(readOnly = false)
	public void updateUsers(Users user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			entryptPassword(user);
		}
		usersDao.save(user);
	}

	@Transactional(readOnly = false)
	public void deleteUser(String id) {
		if (id.equals("admin")) {
			// logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		usersDao.delete(usersDao.findOne(id));
	}

	public List<Users> getAllUsers() {
		return (List<Users>) usersDao.findAll();
	}

	public Page<Users> getUsersList(Map<String, Object> searchParams,
			int pageNumber, int pageSize, String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize,
				sortType);
		Specification<Users> spec = buildSpecification(searchParams);

		return usersDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize,
			String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "userId");
		} else if ("title".equals(sortType)) {
			sort = new Sort(Direction.ASC, "userId");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Users> buildSpecification(
			Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<Users> spec = DynamicSpecifications.bySearchFilter(
				filters.values(), Users.class);
		return spec;
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(Users user) {
		if (AppContants.HASH_ALGORITHM.equals("MD5")) {
			user.setPassword(SecurityUtils.md5(user.getPassword()));
		} else if (AppContants.HASH_ALGORITHM.equals("SHA-1")) {
			byte[] salt = Digests.generateSalt(AppContants.SALT_SIZE);
			user.setSalt(Encodes.encodeHex(salt));

			byte[] hashPassword = Digests.sha1(user.getPlainPassword()
					.getBytes(), salt, AppContants.HASH_INTERATIONS);
			user.setPassword(Encodes.encodeHex(hashPassword));
		}
	}
}
